from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import Http404

import logging

from google.appengine.api import users
from google.appengine.ext.db import djangoforms

from memebase.models import Site

from memebase.utils import requires_logged_user

log = logging.getLogger('memebase.views.sites')
log.setLevel(logging.DEBUG)

     
def requires_existing_site(view):
    # requires python 2.5 or greater
    from functools import wraps
    @wraps(view)
    def view_func(request, *args, **kw):
        # accept a sitename as keyword or as first argument after request
        sitename = kw.get('sitename')
        if not sitename and args and args[0]:
            sitename = args[0]
        site = Site.get_site_by_name(sitename)
        if not site:
            raise Http404
        return view(request, site, *args, **kw)
    return view_func


def main(request):
    log.debug('Returning main view')
    user = users.get_current_user()
    login_url = users.create_login_url(request.META['PATH_INFO'])
    logout_url = users.create_logout_url(request.META['PATH_INFO'])
    sites = Site.get_all_sites()
    return render_to_response('memebase/main.html', locals())


@requires_logged_user(google_admin=True)
def create_site(request):
    class SiteCreateForm(djangoforms.ModelForm):
        name = djangoforms.forms.CharField(label='Site name', max_length=20, required=True)
        admin = djangoforms.forms.EmailField(label='Admin email', help_text='Google account for new admin')
        class Meta:
            model = Site
            fields = ['admin']
        def clean_name(self):
            name = form.cleaned_data['name']
            site = Site.get_site_by_name(name)
            if site:
                raise djangoforms.forms.ValidationError('Site name %s already exists' % name)
            return name
        def save(self, commit=True):
            name = self.cleaned_data['name']
            admin = self.cleaned_data['admin']
            site = Site.create(name=name, admin=admin)
            if not site:
                self.errors['__all__'] = 'Error saving new Site, invalid name'
            return site
    if request.method == 'GET':
        form = SiteCreateForm()
        return render_to_response('memebase/create_site.html', locals())
    elif request.method == 'POST':
        form = SiteCreateForm(request.POST)
        if form.is_valid():
            site = form.save()
            if site:
                return HttpResponseRedirect(site.get_site_prefix())
            else:
                # Probably site name collision
                log.warning('Unknown form error creating site. Form: "%s"', form.cleaned_data)
        return render_to_response('memebase/create_site.html', locals())


@requires_existing_site
def view_site(request, site, sitename):
    user = users.get_current_user()
    memes = site.get_all_visible_memes(user)
    user_can_create_meme = site.can_create_meme(user)
    if user_can_create_meme:
        from memebase.views.memes import get_MemeCreateForm
        form_create = get_MemeCreateForm(user, site)()
    return render_to_response('memebase/site_main.html', locals())

@requires_logged_user(google_admin=True)
def clean_root(request):
    from memebase.models import Root
    Root.clean_all_content()
    return HttpResponseRedirect(reverse('main'))


def list_sites(request):
    sites = Site.get_all_sites()
    return render_to_response('memebase/list_sites.html', locals())

